package com.library.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.library.dao.DAOFactory;
import com.library.dao.MySQLDAOFactory;
import com.library.dao.User;
import com.library.dao.UserDAO;

/**
 * Servlet implementation class HandleCheckAvalability
 */
@WebServlet("/HandleCheckAvalability")
public class HandleCheckAvalability extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HandleCheckAvalability() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		String id = request.getParameter("id");
		String pass = request.getParameter("pass");
		Enumeration<String> p = request.getParameterNames();
		String s = p.toString();
		response.setContentType("text/html");
		try{
			int userId = Integer.parseInt(id);
			DAOFactory factory = new MySQLDAOFactory();
			UserDAO userDao = factory.getUserDAO();
			User user = userDao.findUser(userId);
			if (user == null)
				response.getWriter().write("ID không tồn tại");
			else if (user.getPassword().equals(pass))
				response.getWriter().write("Nhập sai password");
			else
				response.getWriter().write("o");
		} catch(Exception e){
			response.getWriter().write("ID không phải là một số");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String pass = request.getParameter("pass");
		response.setContentType("text/html");
		try{
			int userId = Integer.parseInt(id);
			DAOFactory factory = new MySQLDAOFactory();
			UserDAO userDao = factory.getUserDAO();
			User user = userDao.findUser(userId);
			if (user == null)
				response.getWriter().write("ID không tồn tại");
			else if (user.getPassword().equals(pass))
				response.getWriter().write("Nhập sai password");
			else 
				response.getWriter().write("");
		} catch(Exception e){
			response.getWriter().write("ID không phải là một số");
		}
	}

}
